//
//  UIViewController+CLGExtension.m
//  NativeWebDemo
//
//  Created by GuochengLiu on 2017/2/8.
//  Copyright © 2017年 sumavision. All rights reserved.
//

#import "UIViewController+CLGExtension.h"
#import <objc/runtime.h>

@implementation UIViewController (CLGExtension)

- (instancetype)initWithParamDict:(NSDictionary *)paramDict
{
    self = [self initWithNibName:NSStringFromClass(self.class) bundle:nil];
    if (self) {
        NSArray *allPropertyNames = [self allPropertyNames];
        for (NSString *propertyName in allPropertyNames) {
            id value = [paramDict valueForKey:propertyName];
            if (value != nil) {
                [self setValue:value forKey:propertyName];
            }
        }
    }
    return self;
}

- (NSArray *)allPropertyNames
{
    unsigned count;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    
    NSMutableArray *rv = [NSMutableArray array];
    
    unsigned i;
    for (i = 0; i < count; i++)
    {
        objc_property_t property = properties[i];
        NSString *name = [NSString stringWithUTF8String:property_getName(property)];
        [rv addObject:name];
    }
    
    free(properties);
    
    return rv;
}

- (void)showLoadingSpinner
{
    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [spinner setCenter:self.view.center];
    [self.view addSubview:spinner];
    
    [spinner startAnimating];
}


- (void)dismissLoadingSpinner
{
    for (UIView *view in self.view.subviews) {
        if ([view isKindOfClass:[UIActivityIndicatorView class]]) {
            [(UIActivityIndicatorView *)view stopAnimating];
            [view removeFromSuperview];
        }
    }
}

@end
